import http,MySQLdb,pdb
from .. import config
from . import postutils


personLine='<p>%s</p><br />'
def wantMyself(handler):
    handler.send_response(http.HTTPStatus.OK)
    handler.send_header('Content-Type','html')
    handler.end_headers()
    f=open('./sites/wantMyself.html','r')
    template=f.read()
    f.close()
    headings,tail=template.split('<!--SPLIT-->')
    db=MySQLdb.connect('localhost','ken','ken0417','images')
    cursor=db.cursor()
    cursor.execute('select person from untaken')
    untakens=cursor.fetchall()
    body=''
    for person in untakens:
        body+=personLine%person[0]
    html=headings+body+tail
    handler.wfile.write(html.encode())


def handle_wanted_data(handler):
    try:
        parsed=postutils.parse(handler)
        #pdb.set_trace()
        name=postutils.get_content(*parsed[1:-1])[0].decode()
        assert config.dangers.match(name)==None
        db=MySQLdb.connect('localhost','ken','ken0417','images')
        db.autocommit(True)
        cursor=db.cursor()
        cursor.execute('insert into untaken value ("{person}");'.format(person=name))
        db.close()
        handler.send_response(http.HTTPStatus.SEE_OTHER)
        handler.send_header('Location','/')
        handler.end_headers()
    except BaseException:
        raise
        handler.send_response(http.HTTPStatus.INTERNAL_SERVER_ERROR)


